package com.topwalk.step01;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

/**
 * blocked与runnable的转换
 * 
 * @author tang
 */
@Slf4j
public class Demo4_3TimedWaiting2Runnable {

    @Test
    public void blockedTest() throws InterruptedException {

        Thread a = new Thread(this::testMethod, "a");
        Thread b = new Thread(this::testMethod, "b");

        a.start();
        a.join(1000L);
        b.start();
       
        log.debug(a.getName() + ":" + a.getState()); // 输出 TERMINATED
        log.debug(b.getName() + ":" + b.getState()); // 输出 TIMED_WAITING
    }

    // 同步方法争夺锁
    private synchronized void testMethod() {
        try {
            String name = Thread.currentThread().getName();
            log.info("{} begin", name);
            Thread.sleep(2000L);
            log.info("{} end", name);
        } catch (InterruptedException e) {
            log.error("", e);
            Thread.currentThread().interrupt();
        }
    }
    
}
